package com.menker.app.biz;


import android.Manifest;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.google.gson.Gson;
import com.menker.app.Constants;
import com.menker.app.R;
import com.menker.app.common.BaseWebViewToolbarActivity;
import com.menker.app.common.SharedPreferencesHelper;
import com.menker.app.common.ToolbarOwner;
import com.menker.app.common.Utils;
import com.menker.app.dao.ItemDAO;
import com.menker.app.rest.ApiHelper;
import com.menker.app.rest.result.ApiResult;
import com.menker.app.rest.result.AppInfo;
import com.menker.app.rest.result.LoginResult;
import com.menker.app.rest.result.ProductShareInfo;
import com.menker.app.sharesdk.OnLoginListener;
import com.menker.app.sharesdk.ThirdPartyLoginApi;
import com.menker.app.sharesdk.UserInfo;
import com.menker.app.ui.generalweb.GeneralWebViewActivity;
import com.menker.app.ui.main.MainActivity;
import com.menker.app.util.AppUtils;
import com.menker.app.util.IntentUtils;
import com.menker.app.util.ShareUtils;
import com.menker.app.util.TaobaoUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.wechat.friends.Wechat;

import myandroid.library.util.ApplicationHelper;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import rx.Subscriber;

public class JsBridgeHelper {

    private Activity mActivity;
    private ToolbarOwner.IToolbar mToolbar;
    private BridgeWebView mWebView;
    private LocationClient mLocationClient;

    private ApiHelper mApiHelper;
    private CurrentUser mCurrentUser;

    private String mStrErrorApi;

    public JsBridgeHelper(Activity activity,
                          ToolbarOwner.IToolbar toolbar,
                          BridgeWebView webView,
                          ApiHelper apiHelper,
                          CurrentUser currentUser) {
        mActivity = activity;
        mToolbar = toolbar;
        mWebView = webView;

        mApiHelper = apiHelper;
        mCurrentUser = currentUser;

        initAll();
    }

    private void initAll() {
        mStrErrorApi = mActivity.getString(R.string.error_api);

        mWebView.registerHandler("APP.closePage", mHandlerClosePage);

        mWebView.registerHandler("APP.thirdLogin", mHandlerThirdLogin);
        mWebView.registerHandler("APP.logout", mHandlerLogout);

        mWebView.registerHandler("APP.UrlCommon", mHandlerCommonUrl);

        mWebView.registerHandler("APP.setTicket", mHandlerSetTicket);
        mWebView.registerHandler("APP.getTicket", mHandlerGetTicket);
        mWebView.registerHandler("APP.setData", mHandlerSetData);
        mWebView.registerHandler("APP.getData", mHandlerGetData);

        mWebView.registerHandler("APP.saveOrder", mHandlerSaveOrder);
        mWebView.registerHandler("APP.requestLocation", mHandlerRequestLocation);
        mWebView.registerHandler("APP.checkAppUpdate", mHandlerCheckAppUpdate);
        mWebView.registerHandler("APP.makeCall", mHandlerMakeCall);
        mWebView.registerHandler("APP.showShareMenu", mHandlerShowShareMenu);

        mWebView.registerHandler("APP.upload", mHandlerUpload);

        mWebView.registerHandler("APP.setEventInfo", mHandlerSetEventInfo);
        mWebView.registerHandler("APP.enablePullToRefresh", mHandlerEnablePullToRefresh);
        mWebView.registerHandler("APP.proxy", mHandlerProxy);
        mWebView.registerHandler("APP.setPageTitle", mHandlerSetPageTitle);
        mWebView.registerHandler("APP.isWeixinAvailable", mHandlerWeixinAvailable);

        mWebView.registerHandler("APP.setCurrentProduct", mHandlerSetCurrentProduct);
        mWebView.registerHandler("APP.viewProduct", mHandlerViewProduct);

        mWebView.registerHandler("APP.shareImage", mHandlerSharePic);

    }

    public void setLocationClient(LocationClient client) {
        if (client != null) {
            mLocationClient = client;
            mLocationClient.registerLocationListener(new MyLocationListener());
        }
    }

    public void destroy() {
    }

    private BridgeHandler mHandlerClosePage = new BridgeHandler() {
        @Override
        public void handler(String data, CallBackFunction function) {
            function.onCallBack("true");

            mActivity.finish();
            ApplicationHelper.getInstance().removeActivity(mActivity);
        }
    };

    private BridgeHandler mHandlerThirdLogin = new BridgeHandler() {
        @Override
        public void handler(String data, CallBackFunction function) {
            if (mActivity != null && data != null) {
                String platformName;
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    platformName = jsonObject.getString("platformName");
                } catch (JSONException e) {
                    platformName = "";
                }

                if ("wechat".equalsIgnoreCase(platformName)) {

                    if (!AppUtils.isWechatAppInstalledAndSupported(mActivity)) {
                        Utils.UI.showToastLong("微信登录失败！\n目前您的微信版本过低或未安装微信");
                        function.onCallBack("false");
                        return;
                    }

                    ThirdPartyLoginApi api = new ThirdPartyLoginApi();
                    //设置登陆的平台后执行登陆的方法
                    api.setPlatform(Wechat.NAME);
                    api.setOnLoginListener(new OnLoginListener() {
                        public boolean onLogin(String platform, HashMap<String, Object> res, String token) {
                            // 在这个方法填写尝试的代码，返回true表示还不能登录，需要注册
                            // 此处全部给回需要注册

                            String openId = (String) res.get("openid");
                            String nickName = (String) res.get("nickname");
                            String avatar = (String) res.get("headimgurl");

                            String platformCode = Constants.PLATFORM.WECHAT;

                            mApiHelper.thirdLogin(new ThirdLoginSubscriber(),
                                    openId, platformCode, token, nickName, avatar, "");

                            return false;
                        }

                        public boolean onRegister(UserInfo info) {
                            // 填写处理注册信息的代码，返回true表示数据合法，注册页面可以关闭
                            return true;
                        }
                    });

                    Utils.UI.showToastLong("登录操作后台进行中,请稍候...");
                    api.login(mActivity);

                    function.onCallBack("true");
                } else {
                    function.onCallBack("false");
                }
            } else {
                function.onCallBack("false");
            }
        }
    };

    private BridgeHandler mHandlerLogout = new BridgeHandler() {
        @Override
        public void handler(String data, CallBackFunction function) {
            mCurrentUser.logout();
            function.onCallBack("true");
            IntentUtils.toLogin(mActivity);
        }
    };

    private BridgeHandler mHandlerCommonUrl = new BridgeHandler() {
        @Override
        public void handler(String data, CallBackFunction function) {
            try {
                JSONObject jsonObject = new JSONObject(data);
                String url = jsonObject.getString("url");
                String target = jsonObject.getString("target");

                if (!TextUtils.isEmpty(url) && !TextUtils.isEmpty(target)) {
                    if (target.equals("_blank")) {
                        if (mActivity != null) {
                            WebPageInfo webPageInfo = new WebPageInfo("", url);
                            IntentUtils.toNewGeneralWebViewActivity(mActivity, webPageInfo);
                            function.onCallBack("true");
                        } else {
                            function.onCallBack("false");
                        }
                    } else if (target.equals("_self")) {
                        mWebView.loadUrl(url);
                        function.onCallBack("true");
                    }
                } else {
                    function.onCallBack("false");
                }
            } catch (JSONException e) {
                e.printStackTrace();
                function.onCallBack("true");
            }
        }
    };

    private BridgeHandler mHandlerSetTicket = new BridgeHandler() {
        @Override
        public void handler(String data, CallBackFunction function) {
            if (mActivity != null && data != null) {
                String ticket;
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    ticket = jsonObject.getString("ticket");
                    mCurrentUser.setSyncId(ticket);

                    function.onCallBack("true");
                } catch (JSONException e) {
                    function.onCallBack("false");
                }
            }
        }
    };

    private BridgeHandler mHandlerGetTicket = new BridgeHandler() {
        @Override
        public void handler(String data, CallBackFunction function) {
            String ticket = "";

            if (mActivity != null && mCurrentUser != null) {
                ticket = mCurrentUser.getSyncId();
            }

            function.onCallBack(ticket);
        }
    };

    private BridgeHandler mHandlerSaveOrder = new BridgeHandler() {
        @Override
        public void handler(String data, CallBackFunction function) {
            if (mActivity != null && data != null && mApiHelper != null) {
                mApiHelper.createOrder(new CreateOrderSubscriber(), data);
                function.onCallBack("true");
            } else {
                function.onCallBack("false");
            }
        }
    };

    private BridgeHandler mHandlerSetData = new BridgeHandler() {
        @Override
        public void handler(String data, CallBackFunction function) {
            try {
                JSONObject jsonObject = new JSONObject(data);
                String key = jsonObject.getString("key");
                String val = jsonObject.getString("val");
                if (!TextUtils.isEmpty(key) && val != null) {
                    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mActivity);
                    sharedPreferences.edit().putString(key, val).commit();
                    function.onCallBack("true");
                } else {
                    function.onCallBack("false");
                }
            } catch (JSONException e) {
                e.printStackTrace();
                function.onCallBack("false");
            }
        }
    };

    private BridgeHandler mHandlerGetData = new BridgeHandler() {
        @Override
        public void handler(String data, CallBackFunction function) {
            try {
                JSONObject jsonObject = new JSONObject(data);
                String key = jsonObject.getString("key");
                if (!TextUtils.isEmpty(key) && mActivity != null) {
                    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(mActivity);
                    String value = sharedPref.getString(key, "");
                    function.onCallBack(value);
                } else {
                    function.onCallBack("");
                }
            } catch (JSONException e) {
                e.printStackTrace();
                function.onCallBack("");
            }
        }
    };

    private BridgeHandler mHandlerRequestLocation = new BridgeHandler() {
        @Override
        public void handler(String data, CallBackFunction function) {
            checkLocationPermission();
        }
    };

    private BridgeHandler mHandlerMakeCall = new BridgeHandler() {
        @Override
        public void handler(String data, CallBackFunction function) {
            try {
                JSONObject jsonObject = new JSONObject(data);
                String tel = jsonObject.getString("tel");
                if (!TextUtils.isEmpty(tel) && mActivity != null) {
                    Intent intent = new Intent();
                    intent.setData(Uri.parse("tel:" + tel));
                    // 不要直接拨打，先跳转到拨号界面
                    intent.setAction(Intent.ACTION_DIAL);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    mActivity.startActivity(intent);

                    function.onCallBack("true");
                } else {
                    function.onCallBack("false");
                }
            } catch (JSONException e) {
                e.printStackTrace();
                function.onCallBack("false");
            }
        }
    };

    private BridgeHandler mHandlerShowShareMenu = new BridgeHandler() {
        @Override
        public void handler(String data, CallBackFunction function) {
            try {
                JSONObject jsonObject = new JSONObject(data);
                String title = jsonObject.getString("title");
                String shareUrl = jsonObject.getString("shareUrl");
                String iconUrl = jsonObject.getString("iconUrl");
                String content = jsonObject.getString("content");

                if (!TextUtils.isEmpty(shareUrl) && mActivity != null) {
                    ShareUtils.showSharePanel(mActivity, new WechatShareManager(mActivity.getApplicationContext()), title, content, shareUrl, iconUrl);

                    ClipboardManager clip = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
                    clip.setPrimaryClip(ClipData.newPlainText(null, content));

                    Utils.UI.showToastLong("内容已复制到剪贴板\n长按即可粘贴获取");

                    function.onCallBack("true");
                } else {
                    function.onCallBack("false");
                }
            } catch (JSONException e) {
                e.printStackTrace();
                function.onCallBack("false");
            }
        }
    };

    private BridgeHandler mHandlerCheckAppUpdate = new BridgeHandler() {
        @Override
        public void handler(String data, CallBackFunction function) {
            if (mActivity != null && mApiHelper != null) {
                checkUpdatePermission();
                function.onCallBack(String.valueOf(Utils.App.getAppVersionCode()));
            } else {
                function.onCallBack("");
            }
        }
    };

    private BridgeHandler mHandlerUpload = new BridgeHandler() {
        @Override
        public void handler(String data, final CallBackFunction function) {
            if (mActivity instanceof GeneralWebViewActivity) {
                ((GeneralWebViewActivity) mActivity).setOnUploadImgListener(new GeneralWebViewActivity.OnUploadImgListener() {
                    @Override
                    public void onFinish(String url) {
                        function.onCallBack(url);
                    }
                });
                ((GeneralWebViewActivity) mActivity).showTakePhotoDialog();
            }
        }
    };

    private BridgeHandler mHandlerSetEventInfo = new BridgeHandler() {
        @Override
        public void handler(String data, CallBackFunction function) {
            if (TextUtils.isEmpty(data)) {
                function.onCallBack("false");
                return;
            }

            try {
                JSONObject jsonObject = new JSONObject(data);
                int num = jsonObject.getInt("num");
                String url = jsonObject.getString("url");

//                if (mActivity instanceof MainActivity) {
//                    BaseToolbarFragment fragment = ((MainActivity) mActivity).getCurrentFragment();
//
//                    if (fragment instanceof HomeFragment) {
//                        ((HomeFragment)fragment).notifySearchView(num,url);
//                    }else if (fragment instanceof TopicFragment) {
//                        ((TopicFragment)fragment).notifySearchView(num,url);
//                    }else if (fragment instanceof ListFragment) {
//                        ((ListFragment)fragment).notifySearchView(num,url);
//                    }
//
//                    function.onCallBack("true");
//                }

                function.onCallBack("false");
            } catch (JSONException e) {
                function.onCallBack("false");
            }
        }
    };

    private BridgeHandler mHandlerEnablePullToRefresh = new BridgeHandler() {
        @Override
        public void handler(String data, CallBackFunction function) {
            if (TextUtils.isEmpty(data)) {
                function.onCallBack("false");
                return;
            }

            try {
                JSONObject jsonObject = new JSONObject(data);
                int state = jsonObject.getInt("state");

                if (mActivity instanceof MainActivity) {
//                    BaseToolbarFragment fragment = ((MainActivity) mActivity).getCurrentFragment();
//                    if (state == 1) {
//                        fragment.setEnableRefresh(true);
//                    }else {
//                        fragment.setEnableRefresh(false);
//                    }
                } else if (mActivity instanceof BaseWebViewToolbarActivity) {
                    BaseWebViewToolbarActivity activity = ((BaseWebViewToolbarActivity) mActivity);
                    if (state == 1) {
                        activity.setEnableRefresh(true);
                    } else {
                        activity.setEnableRefresh(false);
                    }
                }

                function.onCallBack("true");

            } catch (JSONException e) {
                function.onCallBack("false");
            }
        }
    };

    private BridgeHandler mHandlerProxy = new BridgeHandler() {
        @Override
        public void handler(String data, final CallBackFunction function) {
            if (TextUtils.isEmpty(data)) {
                function.onCallBack("false");
                return;
            }

            try {
                JSONObject jsonObject = new JSONObject(data);
                String url = jsonObject.getString("url");

                OkHttpClient client = new OkHttpClient.Builder().build();

                Request request = new Request.Builder()
                        .get()
                        .url(url)
                        .build();

                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        function.onCallBack("false");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String responseStr = response.body().string();

                        mActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                function.onCallBack(responseStr);
                            }
                        });

                    }
                });
            } catch (JSONException e) {
                function.onCallBack("false");
            }
        }
    };

    private BridgeHandler mHandlerSetPageTitle = new BridgeHandler() {
        @Override
        public void handler(String data, final CallBackFunction function) {
            if (TextUtils.isEmpty(data)) {
                function.onCallBack("false");
                return;
            }

            try {
                JSONObject jsonObject = new JSONObject(data);
                String title = jsonObject.getString("title");

                if (mActivity instanceof GeneralWebViewActivity) {
                    ((GeneralWebViewActivity) mActivity).setTitleByJS(title);
                }
            } catch (JSONException e) {
                function.onCallBack("false");
            }
        }
    };

    private BridgeHandler mHandlerWeixinAvailable = new BridgeHandler() {
        @Override
        public void handler(String data, CallBackFunction function) {
            if (AppUtils.isWechatAppInstalledAndSupported(mActivity)) {
                function.onCallBack("true");
            } else {
                function.onCallBack("false");
            }
        }
    };

    private BridgeHandler mHandlerSetCurrentProduct = new BridgeHandler() {
        @Override
        public void handler(String data, CallBackFunction function) {

        }
    };

    private BridgeHandler mHandlerViewProduct = new BridgeHandler() {
        @Override
        public void handler(String data, CallBackFunction function) {
            if (TextUtils.isEmpty(data)) {
                function.onCallBack("false");
                return;
            }

            try {
                JSONObject jsonObject = new JSONObject(data);
                ProductShareInfo shareInfo = new ProductShareInfo();

                String pid = jsonObject.getString("pid");
                shareInfo.itemId = pid;
                shareInfo.price = jsonObject.getDouble("price");
                shareInfo.content = jsonObject.getString("content");
                shareInfo.shareUrl = jsonObject.getString("shareUrl");
                shareInfo.title = jsonObject.getString("title");
                shareInfo.imgUrl = jsonObject.getString("iconUrl");

//                if (mActivity instanceof GeneralWebViewActivity) {
//                    ((GeneralWebViewActivity)mActivity).setProductShareInfo(shareInfo);
//                }
                mCurrentUser.setmShareInfo(shareInfo);

                long curTime = System.currentTimeMillis();
                ItemDAO dao = new ItemDAO(mActivity);
                List<ItemInfo> itemList = dao.queryData(pid);
                if (itemList == null || itemList.size() == 0) {
                    dao.insertData(curTime, pid);
                } else {
                    dao.changeData(pid, curTime);
                }

            } catch (JSONException e) {
                e.printStackTrace();
                function.onCallBack("false");
            }
        }
    };

    private BridgeHandler mHandlerSharePic = new BridgeHandler() {

        @Override
        public void handler(String data, final CallBackFunction function) {
            if (mActivity instanceof GeneralWebViewActivity) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    String imgUrl = jsonObject.getString("imageUrl");

                    ((GeneralWebViewActivity) mActivity).setOnSharePicListener(new GeneralWebViewActivity.OnSharePicListener() {
                        @Override
                        public void onShareFinished(boolean shareSuccess, Platform platform) {
                            try {
                                String name = platform.getName();
                                if ("Wechat".equals(name)) {
                                    name = "WechatSession";
                                } else if ("WechatMoments".equals(name)) {
                                    name = "WechatTimeline";
                                } else {
                                    name = "Other";
                                }
                                final JSONObject object = new JSONObject();
                                object.put("res", shareSuccess);
                                object.put("platform", name);
                                final String jsonStr = object.toString();

                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            Thread.currentThread().join(100);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                        mActivity.runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                function.onCallBack(jsonStr);
                                            }
                                        });
                                    }
                                }).start();

//                                if (mActivity instanceof GeneralWebViewActivity) {
//                                    ((GeneralWebViewActivity)mActivity).shareCallback(jsonStr);
//                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });

                    ((GeneralWebViewActivity) mActivity).sharePic(imgUrl);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    public void onWebShow() {
        mWebView.callHandler("WEB.onShow", null, null);
    }

    public void shareCallback(final String data) {
        mWebView.callHandler("WEB.shareCallback", data, null);
    }

    private static final int BAIDU_LOCATION = 100;
    private static final int APP_UPDATE = 110;

    private void checkUpdatePermission() {
        BaseWebViewToolbarActivity activity;
        if (mActivity instanceof BaseWebViewToolbarActivity) {
            activity = ((BaseWebViewToolbarActivity) mActivity);
        } else {
            return;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (activity.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    ) {

                activity.setOnRequestPermissionListener(new BaseWebViewToolbarActivity.OnRequestPermissionListener() {
                                                            @Override
                                                            public void onSuccess() {
                                                                mApiHelper.getAppInfo(new GetAppInfoSubscriber());
                                                            }
                                                        },
                        "应用升级功能无法使用!\n请在\"设置\"中开启存储卡权限",
                        APP_UPDATE);

                activity.requestPermissions(new String[]{
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                }, APP_UPDATE);
            } else {
                mApiHelper.getAppInfo(new GetAppInfoSubscriber());
            }
        } else {
            mApiHelper.getAppInfo(new GetAppInfoSubscriber());
        }
    }

    private void checkLocationPermission() {

        BaseWebViewToolbarActivity activity;
        if (mActivity instanceof BaseWebViewToolbarActivity) {
            activity = ((BaseWebViewToolbarActivity) mActivity);
        } else {
            return;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            LocationManager locManager = (LocationManager) mActivity.getSystemService(Context.LOCATION_SERVICE);
            if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                // 未打开位置开关，可能导致定位失败或定位不准，提示用户或做相应处理
                Utils.UI.showToastLong("未打开位置开关，可能导致定位失败或定位不准");
            }

            if (activity.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    || activity.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    ) {

                activity.setOnRequestPermissionListener(new BaseWebViewToolbarActivity.OnRequestPermissionListener() {
                                                            @Override
                                                            public void onSuccess() {
                                                                initLocation();
                                                            }
                                                        },
                        "应用无法根据您的位置提供更精准的优惠商品\n请在\"设置\"中开启定位权限",
                        BAIDU_LOCATION);

                activity.requestPermissions(new String[]{
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                }, BAIDU_LOCATION);

            } else {
                initLocation();
            }
        } else {
            initLocation();
        }
    }

    private void initLocation() {
        if (mLocationClient != null) {
            mLocationClient.start();
        }
    }

    private void fetchAreaFromAddr(BDLocation bdLocation) {

        LocationInfo locationInfo = new LocationInfo();

        locationInfo.provice = bdLocation.getProvince();
        locationInfo.city = bdLocation.getCity();
        locationInfo.street = bdLocation.getStreet();
        locationInfo.district = bdLocation.getDistrict();
        locationInfo.lat = bdLocation.getLatitude();
        locationInfo.lng = bdLocation.getLongitude();

        mWebView.callHandler("WEB.setLocation", new Gson().toJson(locationInfo), null);
    }

    private class MyLocationListener extends BDAbstractLocationListener {

        @Override
        public void onLocDiagnosticMessage(int i, int i1, String s) {
            if (i1 == LocationClient.LOC_DIAGNOSTIC_TYPE_BETTER_OPEN_GPS) {
                //建议打开GPS
                Utils.UI.showToastShort("建议打开GPS");
            } else if (i1 == LocationClient.LOC_DIAGNOSTIC_TYPE_BETTER_OPEN_WIFI) {
                //建议打开wifi，不必连接，这样有助于提高网络定位精度！
                Utils.UI.showToastShort("建议打开wifi，不必连接，这样有助于提高网络定位精度！");
            } else if (i1 == LocationClient.LOC_DIAGNOSTIC_TYPE_NEED_CHECK_LOC_PERMISSION) {
                //定位权限受限，建议提示用户授予APP定位权限！
            } else if (i1 == LocationClient.LOC_DIAGNOSTIC_TYPE_NEED_CHECK_NET) {
                //网络异常造成定位失败，建议用户确认网络状态是否异常！
                Utils.UI.showToastShort("网络异常造成定位失败，建议确认网络状态是否异常！");
            } else if (i1 == LocationClient.LOC_DIAGNOSTIC_TYPE_NEED_CLOSE_FLYMODE) {
                //手机飞行模式造成定位失败，建议用户关闭飞行模式后再重试定位！
                Utils.UI.showToastShort("手机飞行模式造成定位失败，建议关闭飞行模式后再重试定位！");
            } else if (i1 == LocationClient.LOC_DIAGNOSTIC_TYPE_NEED_INSERT_SIMCARD_OR_OPEN_WIFI) {
                //无法获取任何定位依据，建议用户打开wifi或者插入sim卡重试！
                Utils.UI.showToastShort("无法获取任何定位依据，建议打开wifi或者插入sim卡重试！");
            } else if (i1 == LocationClient.LOC_DIAGNOSTIC_TYPE_NEED_OPEN_PHONE_LOC_SWITCH) {
                //无法获取有效定位依据，建议用户打开手机设置里的定位开关后重试！
                Utils.UI.showToastShort("无法获取有效定位依据，建议打开手机设置里的定位开关后重试！");
            } else if (i1 == LocationClient.LOC_DIAGNOSTIC_TYPE_SERVER_FAIL) {
                //百度定位服务端定位失败
                //建议反馈location.getLocationID()和大体定位时间到loc-bugs@baidu.com
            } else if (i1 == LocationClient.LOC_DIAGNOSTIC_TYPE_FAIL_UNKNOWN) {
                //无法获取有效定位依据，但无法确定具体原因
                //建议检查是否有安全软件屏蔽相关定位权限
                //或调用LocationClient.restart()重新启动后重试！
            }
        }

        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (bdLocation.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                fetchAreaFromAddr(bdLocation);
            } else if (bdLocation.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                fetchAreaFromAddr(bdLocation);
            } else if (bdLocation.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                fetchAreaFromAddr(bdLocation);
            } else if (bdLocation.getLocType() == BDLocation.TypeServerError) {
                Utils.UI.showToastShort("定位失败！请稍候再试");
            } else if (bdLocation.getLocType() == BDLocation.TypeNetWorkException) {
                Utils.UI.showToastShort("网络不同导致定位失败，请检查网络是否通畅");
            } else if (bdLocation.getLocType() == BDLocation.TypeCriteriaException) {
                Utils.UI.showToastShort("无法获取有效定位依据导致定位失败，请关闭飞行模式或重启手机");
            }
        }
    }

    private class ThirdLoginSubscriber extends Subscriber<LoginResult> {
        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            Utils.UI.showToastShort(mStrErrorApi);
        }

        @Override
        public void onNext(final LoginResult loginResult) {
            if (loginResult.checkState(mActivity) && !TextUtils.isEmpty(loginResult.Ticket)) {
                SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(mActivity);
                sharedPref.edit().putString(Constants.API.KEY_TICKET, loginResult.Ticket).apply();

                IntentUtils.toMainActivity(mActivity);
            } else {
                Utils.UI.showToastLong("未绑定账户");
//                Utils.UI.showToastShort(mStrErrorApi);
            }
        }
    }

    private class CreateOrderSubscriber extends Subscriber<ApiResult> {
        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            Utils.UI.showToastShort(mStrErrorApi);
        }

        @Override
        public void onNext(final ApiResult apiResult) {
            if (apiResult.checkState(mActivity)) {
            } else {
                Utils.UI.showToastShort(mStrErrorApi);
            }
        }
    }

    private class GetAppInfoSubscriber extends Subscriber<AppInfo> {
        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            Utils.UI.showToastShort(mStrErrorApi);
        }

        @Override
        public void onNext(final AppInfo appInfo) {
            if (appInfo.checkState(mActivity)) {
                mCurrentUser.setAppInfo(appInfo);
                AppUtils.manualCheckVersion(mActivity, appInfo.AppVersion, appInfo.AppUrl, appInfo.ForceUpdate, new SharedPreferencesHelper(mActivity));
            } else {
                Utils.UI.showToastShort(mStrErrorApi);
            }
        }
    }
}
